﻿using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Web;
using System.Web.Services;
using System.Web.UI;
using System.Web.UI.WebControls;

public partial class Login : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        string[] states = File.ReadAllLines(Server.MapPath("~/App_Data/UserCreationData/states.txt"));
        string[] carriers = File.ReadAllLines(Server.MapPath("~/App_Data/UserCreationData/carriers.txt"));

        if (statesCB.Items.Count == 0 && carrierCB.Items.Count == 0)
        {
            statesCB.Items.Add("");
            carrierCB.Items.Add("");

            for (int i = 0; i < states.Length; i++) //Build the states drop down
                statesCB.Items.Add(states[i]);

            for (int i = 0; i < carriers.Length; i++) //Build the carriers drop down
                carrierCB.Items.Add(carriers[i]);
        }
    }
    protected void loginB_Click(object sender, EventArgs e)
    {
        login();
    }
    [WebMethod]
    public static bool CheckUserExists(string jEmailAddress) //Checks to make sure the email address exists or not
    {
        string emailAddress = jEmailAddress;
        string connectionStr = ConfigurationManager.ConnectionStrings[1].ConnectionString;
        string checkForUserStr = "SELECT email_address FROM [user] WHERE email_address = '" + emailAddress + "'";
        bool exists = false;
        SqlConnection cn = new SqlConnection(connectionStr);
        SqlCommand command = new SqlCommand(checkForUserStr, cn);
        SqlDataReader dataReader = null;
        
        if (String.IsNullOrEmpty(emailAddress) == false)
        {
            try
            {
                cn.Open();
                dataReader = command.ExecuteReader();

                if (dataReader.Read() == false)
                    exists = false;
                else
                    exists = true;
                dataReader.Close();
                cn.Close();
            }
            catch (Exception e)
            {
                MessageBox.Show(e.Message);
            }
        }
        return exists;
    }
    //Method that checks the user's credentials with the database and goes to the main page if successful
    private void login()
    {
        try
        {
            if (userTF.Text.Equals("") || passwordTF.Text.Equals("")) //Checks if the username or password is empty
            {
                string errorStr = "Email address or password is missing";
                MessageBox.Show(errorStr);
                return;
            }
            /*
             * Creates a SQL connection and checksthe information entered in with the database records
             * If no match is found it will display the error
             * Otherwise it will go to the MainPage.aspx site
             */
            //Start
            string emailAddress = userTF.Text;
            string password = passwordTF.Text;
            string SQLuser = null;
            string SQLPassword = null;

            string connectionStr = ConfigurationManager.ConnectionStrings[1].ConnectionString;
            SqlConnection cn = new SqlConnection(connectionStr);
            SqlCommand command = new SqlCommand("SELECT * FROM [user] WHERE email_address = '" + emailAddress + "' AND email_password = '" + password + "'", cn);
            SqlDataReader dataReader = null;
            cn.Open();
            dataReader = command.ExecuteReader();
            while (dataReader.Read())
            {
                Session["userID"] = (int)dataReader.GetSqlInt32(0);
                Session["firstName"] = dataReader.GetString(1);
                Session["lastName"] = dataReader.GetString(2);
                Session["emailAddress"] = SQLuser;
                Session["address"] = dataReader.GetString(5);
                Session["city"] = dataReader.GetString(6);
                Session["state"] = dataReader.GetString(7);
                Session["zipCode"] = dataReader.GetInt32(8);
                Session["phoneNumber"] = dataReader.GetString(9);
                Session["phoneCarrier"] = dataReader.GetString(10);
                
                SQLuser = dataReader.GetString(3);
                SQLPassword = dataReader.GetString(4);
            }
            if (emailAddress.Equals(SQLuser) && password.Equals(SQLPassword))
            {
                Response.Redirect("MainPage.aspx");
            }
            else
                MessageBox.Show("Login Failed");

            dataReader.Close();
            cn.Close();
            //End
        }
        catch (Exception evt)
        { 
            Response.Write("<div><p><font color=\"red\">Error: ");
            Response.Write(evt.Message);
            Response.Write("</font></p></div>");
        }
    }
    private bool controlsFilledOut() //Makes sure that all items have been entered in before creating a user
    {
        if (firstNameTF.Text == String.Empty)
            return false;
        else if (lastNameTF.Text == String.Empty)
            return false;
        else if (emailTF.Text == String.Empty)
            return false;
        else if (passwordTF.Text == String.Empty)
            return false;
        else if (addressTF.Text == String.Empty)
            return false;
        else if (cityTF.Text == String.Empty)
            return false;
        else if (statesCB.SelectedItem.Text == String.Empty)
            return false;
        else if (phoneNumTF.Text == String.Empty)
            return false;
        else if (carrierCB.SelectedItem.Text == String.Empty)
            return false;
        else
            return true;
    }
    //Method that takes information from Client AJAX call and inserts the information into the database
    //Client-side JavaScript makes sure the integrity of the data is in tact before transferred to server
    [WebMethod]
    public static String CreateUser(string jFirstName, string jLastName, string jEmailAddress, string jPassword, string jAddress, string jCity, string jState, string jPhoneNum, int jZip, string jCarrier)
    {
        /*
         * Check that all parameters have values
         */
        //Start
        if (jFirstName == "")
            return "First Name field not filled out";
        else if (String.IsNullOrEmpty(jLastName))
            return "Last Name field not filled out";
        else if (String.IsNullOrEmpty(jEmailAddress))
            return "Email Address field not filled out";
        else if (String.IsNullOrEmpty(jPassword))
            return "Password field not filled out";
        else if (String.IsNullOrEmpty(jAddress))
            return "Address field not filled out";
        else if (String.IsNullOrEmpty(jCity))
            return "City field not filled out";
        else if (String.IsNullOrEmpty(jState))
            return "State field not filled out";
        else if (String.IsNullOrEmpty(jPhoneNum))
            return "Cell number field not filled out";
        else if (jZip == 0)
            return "ZIP field not filled out";
        else if (String.IsNullOrEmpty(jCarrier))
            return "Carrier field not filled out";
        //End
        /*
         * Declare needed variables
         */
        //Start
        string firstname = jFirstName;
        string lastname = jLastName;
        string emailAddress = jEmailAddress;
        string password = jPassword;
        string address = jAddress;
        string city = jCity; 
        string state = jState;
        int zipCode = jZip;
        string phoneNum = jPhoneNum;
        string carrier = jCarrier;
        string createUserStr = "INSERT INTO [user] (first_name, last_name, email_address, email_password, address, city, state, zip_code, phone_number, phone_carrier)" +
                                "VALUES(@first_name,@last_name,@email_address,@email_password,@address,@city,@state,@zip_code,@phone_number,@phone_carrier)";
        //End
        try
        {
            /*
             * Creates connection with SQL and inserts the information into the database to create the account
             */
            //Start
            string connectionStr = ConfigurationManager.ConnectionStrings[1].ConnectionString;
            SqlConnection cn = new SqlConnection(connectionStr);
            SqlCommand command = new SqlCommand(createUserStr);
            cn.ConnectionString = connectionStr;
            cn.Open();

            command.Connection = cn;
            command.Parameters.Add("@first_name", SqlDbType.VarChar, 50).Value = firstname;
            command.Parameters.Add("@last_name", SqlDbType.VarChar, 50).Value = lastname;
            command.Parameters.Add("@email_address", SqlDbType.VarChar, 50).Value = emailAddress;
            command.Parameters.Add("@email_password", SqlDbType.VarChar, 50).Value = password;
            command.Parameters.Add("@address", SqlDbType.VarChar, 50).Value = address;
            command.Parameters.Add("@city", SqlDbType.VarChar, 50).Value = city;
            command.Parameters.Add("@state", SqlDbType.VarChar, 50).Value = state;
            command.Parameters.Add("@zip_code", SqlDbType.Int).Value = zipCode;
            command.Parameters.Add("@phone_number", SqlDbType.VarChar, 50).Value = phoneNum;
            command.Parameters.Add("@phone_carrier", SqlDbType.VarChar, 50).Value = carrier;
            int rows = command.ExecuteNonQuery();
            cn.Close();
            cn.Dispose();
            command.Dispose();
            //End
        }
        catch (Exception e)
        {
            return e.Message;         
        }
        return "Account Created";
    }
}